package org.cornland.systemWarning.schedule;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.cornland.systemWarning.mapper.PtInstanceMapper;
import org.cornland.systemWarning.model.PtInstance;
import org.cornland.systemWarning.model.PtInstanceConfig;
import org.cornland.systemWarning.model.Terrace;
import org.cornland.systemWarning.service.PtInstanceConfigService;
import org.cornland.systemWarning.service.TerraceService;
import org.cornland.systemWarning.utils.AppUrl;
import org.cornland.systemWarning.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class PtInstanceSchedule {

    @Autowired
    AppUrl appUrl;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    PtInstanceMapper ptInstanceMapper;

    @Autowired
    TerraceService terraceService;

    @Autowired
    PtInstanceConfigService ptInstanceConfigService;

    private Boolean flag = false;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");


    @Scheduled(initialDelay= 5000, fixedRate = 60000)
    public void PtInstance(){

        try {
            // 取得设置的下限参数
            PtInstanceConfig ptInstanceConfig = ptInstanceConfigService.selectByPrimaryKey(1);
            //获取开始忽略的时间
            String beganIgnore = ptInstanceConfig.getBeganIgnore();
            //获取忽略结束时间
            String endIgnore = ptInstanceConfig.getEndIgnore();
            //获取当前时间
            String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            boolean isEmpty=false;
            if(StringUtils.isNotBlank(beganIgnore)){
                isEmpty = DateUtil.compareTime(beganIgnore, endIgnore, nowTime);
            }

            // 取下限值
            Double downLimit = ptInstanceConfig.getDownLimit();
            BigDecimal downlimitDec = null;
            if(downLimit!=null){
                downlimitDec = new BigDecimal(downLimit);
                if(downlimitDec.equals(BigDecimal.ZERO)){
                    downlimitDec = new BigDecimal("0.0");
                }
            }

            Double upLimit = ptInstanceConfig.getUpLimit();
            BigDecimal upLimitDec = null;
            if(upLimit!=null){
                upLimitDec = new BigDecimal(upLimit);
            }

            // 所有平台
            List<Terrace> terraces = terraceService.selectAll();

            for (int k = 0; k < terraces.size() ; k++) {
                Terrace terrace = terraces.get(k);
                // 平台id
                Integer id = terrace.getId();
                String tName = terrace.getTName();
                String zyqId = terrace.getZyqId();

                // 得到平台得所有不重复瞬量tag
                List<String> tagList = ptInstanceMapper.getPtInstanceTagsByPtId(id);

                if(tagList.size() == 0){
    //				log.warn(tName +" 未发现瞬量点");

//                    PtInstance last = ptInstanceMapper.getlast(id,0);

                    PtInstance isHandler = ptInstanceMapper.getHave(id,0);

                    // 没在处理中，添加
                    if (Objects.isNull(isHandler)) {
                        PtInstance map = ptInstanceMapper.getData(id,0);
                        Date date = new Date();
                        String format1 = null;
                        String format2 = null;
                        if (Objects.nonNull(map)){
                            format1 = simpleDateFormat.format(date);
                            format2 = simpleDateFormat.format(map.getTime());
                        }
                            // 找不到上一个 直接加
//                        if (last == null && !isEmpty) {
                        //             没数据 或者 数据不是当天的就加
                        if (Objects.isNull(map) || !format1.equals(format2)){
                            PtInstance ptInstance = new PtInstance();
                            ptInstance.setZyqId(zyqId);
                            ptInstance.setTId(id);
                            ptInstance.setTime(new Date());
                            ptInstance.setDescription(tName + " 未发现瞬量点");
                            ptInstance.setFlag(0);
                            ptInstance.setType(0);
                            ptInstanceMapper.insert(ptInstance);
                            continue;
                        } else {
                            LambdaQueryWrapper<PtInstance> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(PtInstance::getZyqId,zyqId);
                            wrapper.eq(PtInstance::getTId,id);
                            wrapper.eq(PtInstance::getTime,map.getTime());
                            wrapper.eq(PtInstance::getDescription,tName + " 未发现瞬量点");
                            wrapper.eq(PtInstance::getFlag,0);
                            wrapper.eq(PtInstance::getType,0);
                            PtInstance ptInstance = new PtInstance().setTime(date);
                            ptInstanceMapper.update(ptInstance,wrapper);
                            continue;

//                            Integer status = map.getFlag();
//
//                            if (status == 1 && !isEmpty) {
//                                PtInstance ptInstance = new PtInstance();
//                                ptInstance.setZyqId(zyqId);
//                                ptInstance.setTId(id);
//                                ptInstance.setTime(new Date());
//                                ptInstance.setDescription(tName + " 未发现瞬量点");
//                                ptInstance.setFlag(0);
//                                ptInstance.setType(0);
//                                ptInstanceMapper.insert(ptInstance);
//                                continue;
//                            } else {
//                                continue;
//                            }
                        }
                    }

//                    if(!flag){
//                        PtInstance ptInstance = new PtInstance();
//                        ptInstance.setZyqId(zyqId);
//                        ptInstance.setTId(id);
//                        ptInstance.setTime(new Date());
//                        ptInstance.setDescription(tName +" 未发现瞬量点");
//                        ptInstance.setFlag(0);
//                        ptInstance.setType(0);
//                        ptInstanceMapper.insert(ptInstance);
//                        continue;
//                    }
//                    else{
//                        continue;
//                    }
                }

                // form:tag1,tag2,tag3
                String tags = "";

                // form组装
                for (int i = 0; i <tagList.size() ; i++) {
                    String tag = tagList.get(i);
                    if(i == tagList.size()-1){
                        tags = tags + tag;
                    }
                    else{
                        tags = tags + tag + ",";
                    }
                }

                // 实时数据接口
                String url = appUrl.queryRealTimeDataUrl + "?tags=" + tags;
                URI uri = URI.create(url);
                String tagString = restTemplate.getForObject(uri, String.class);

                // 转成json array
                JSONArray tagJsonArr = JSONArray.parseArray(tagString);

                // 初始化bigDecimal Array 用于相加
                List<BigDecimal> valueList = new ArrayList<>();

                // count 为 null得点
                int count = 0;

                // 遍历取出每一个value加进Array
                for (int i = 0; i < tagJsonArr.size() ; i++) {
                    Map<String,Object> object = tagJsonArr.getObject(i, Map.class);
                    BigDecimal value = (BigDecimal) object.get("value");
                    if(value != null){
                        valueList.add(value);
                    }
                    else{
                        count++;
                    }
                }

                // 初始化 valusSum 用于sum 所有value
                BigDecimal valueSum = new BigDecimal(0);

                for (int i = 0; i < valueList.size() ; i++) {
                    BigDecimal bigDecimal = valueList.get(i);
                    valueSum = valueSum.add(bigDecimal);
                }

                // 如果总瞬量小于下限值
                if(downlimitDec != null && (valueSum.compareTo(downlimitDec) == -1 || valueSum.equals(downlimitDec))){


//                    PtInstance last = ptInstanceMapper.getlast(id,1);

                    PtInstance isHandler = ptInstanceMapper.getHave(id,1);

                    // 没有信息在未处理或处理中
                    if (Objects.isNull(isHandler)){
                        PtInstance map = ptInstanceMapper.getData(id,1);
                        Date date = new Date();
                        String format1 = null;
                        String format2 = null;
                        if (Objects.nonNull(map)){
                            format1 = simpleDateFormat.format(date);
                            format2 = simpleDateFormat.format(map.getTime());
                        }

                        // 找不到上一个 直接加
//                        if(last == null && !isEmpty){
                            //				log.info(tName+"平台瞬产气量小于"+limit.toString());

                        if (Objects.isNull(map) || !format1.equals(format2)){
                            PtInstance ptInstance = new PtInstance();
                            if(count !=0){
                                //					log.info("其中,有"+count+"个点位为空值");
                                ptInstance.setRemark("其中有"+count+"个瞬量点为null");
                            }
                            ptInstance.setValue(valueSum.doubleValue());
                            ptInstance.setZyqId(zyqId);
                            ptInstance.setTId(id);
                            ptInstance.setTime(new Date());
                            ptInstance.setDescription("平台瞬产气量小于等于"+downLimit.toString());
                            ptInstance.setFlag(0);
                            ptInstance.setType(1);
                            ptInstanceMapper.insert(ptInstance);
                        }
                        else {
                            LambdaQueryWrapper<PtInstance> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(PtInstance::getZyqId,zyqId);
                            wrapper.eq(PtInstance::getTId,id);
                            wrapper.eq(PtInstance::getTime,map.getTime());
                            wrapper.eq(PtInstance::getDescription,"平台瞬产气量小于等于" + downLimit.toString());
                            wrapper.eq(PtInstance::getFlag,0);
                            wrapper.eq(PtInstance::getType,1);
                            PtInstance ptInstance = new PtInstance()
                                    .setTime(date)
                                    .setDescription("平台瞬产气量小于等于" + downLimit.toString());
                            ptInstanceMapper.update(ptInstance,wrapper);

//                            String description = map.getDescription();
//                            Integer status = map.getFlag();
//                            Integer lastId = map.getId();
//
//                            // 上一个已经被处理则添加
//                            if (status == 1 && !isEmpty) {
//                                //				log.info(tName+"平台瞬产气量小于"+limit.toString());
//                                PtInstance ptInstance = new PtInstance();
//                                if (count != 0) {
//                                    //					log.info("其中,有"+count+"个点位为空值");
//                                    ptInstance.setRemark("其中有" + count + "个瞬量点为null");
//                                }
//                                ptInstance.setValue(valueSum.doubleValue());
//                                ptInstance.setZyqId(zyqId);
//                                ptInstance.setTId(id);
//                                ptInstance.setTime(new Date());
//                                ptInstance.setDescription("平台瞬产气量小于等于" + downLimit.toString());
//                                ptInstance.setFlag(0);
//                                ptInstance.setType(1);
//                                ptInstanceMapper.insert(ptInstance);
//                            }
//                            // 上一个未被处理但是 描述不一样也要添加 不处理掉上一个
//                            else if (status == 0 && !description.equals("平台瞬产气量小于等于" + downLimit.toString()) && !isEmpty) {
//                                //				log.info(tName+"平台瞬产气量小于"+limit.toString());
//                                PtInstance ptInstance = new PtInstance();
//                                if (count != 0) {
//                                    //					log.info("其中,有"+count+"个点位为空值");
//                                    ptInstance.setRemark("其中有" + count + "个瞬量点为null");
//                                }
//                                ptInstance.setValue(valueSum.doubleValue());
//                                ptInstance.setZyqId(zyqId);
//                                ptInstance.setTId(id);
//                                ptInstance.setTime(new Date());
//                                ptInstance.setDescription("平台瞬产气量小于等于" + downLimit.toString());
//                                ptInstance.setFlag(0);
//                                ptInstance.setType(1);
//                                ptInstanceMapper.insert(ptInstance);
//
//    //                            ptInstanceMapper.updateLastById(lastId);
//                            }

                        }

                    }


                }
                // 如果总瞬量大于预警上限值
                else if(upLimitDec !=null && (valueSum.compareTo(upLimitDec) == 1 || valueSum.equals(upLimitDec))){


//                    PtInstance last = ptInstanceMapper.getlast(id,1);

                    PtInstance isHandler = ptInstanceMapper.getHave(id,1);

                    // 没有信息在未处理或处理中
                    if (Objects.isNull(isHandler)) {
                        PtInstance map = ptInstanceMapper.getData(id,1);
                        Date date = new Date();
                        String format1 = null;
                        String format2 = null;
                        if (Objects.nonNull(map)){
                            format1 = simpleDateFormat.format(date);
                            format2 = simpleDateFormat.format(map.getTime());
                        }
                        // 找不到上一个 直接加
//                        if(last == null && !isEmpty){
                        if (Objects.isNull(map) || !format1.equals(format2)){
                            PtInstance ptInstance = new PtInstance();
                            if (count != 0) {
                                ptInstance.setRemark("其中有" + count + "个瞬量点为null");
                            }
                            ptInstance.setValue(valueSum.doubleValue());
                            ptInstance.setZyqId(zyqId);
                            ptInstance.setTId(id);
                            ptInstance.setTime(new Date());
                            ptInstance.setDescription("平台瞬产气量大于等于" + upLimit.toString());
                            ptInstance.setFlag(0);
                            ptInstance.setType(1);
                            ptInstanceMapper.insert(ptInstance);
                        } else {
                            LambdaQueryWrapper<PtInstance> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(PtInstance::getZyqId,zyqId);
                            wrapper.eq(PtInstance::getTId,id);
                            wrapper.eq(PtInstance::getTime,map.getTime());
                            wrapper.eq(PtInstance::getDescription,"平台瞬产气量大于等于" + upLimit.toString());
                            wrapper.eq(PtInstance::getFlag,0);
                            wrapper.eq(PtInstance::getType,1);
                            PtInstance ptInstance = new PtInstance()
                                    .setTime(date)
                                    .setDescription("平台瞬产气量大于等于" + upLimit.toString());
                            ptInstanceMapper.update(ptInstance,wrapper);


//                            String description = last.getDescription();
//                            Integer status = last.getFlag();
//                            Integer lastId = last.getId();
//
//
//                            // 上一个已经被处理则添加
//                            if (status == 1 && !isEmpty) {
//                                PtInstance ptInstance = new PtInstance();
//                                if (count != 0) {
//                                    ptInstance.setRemark("其中有" + count + "个瞬量点为null");
//                                }
//                                ptInstance.setValue(valueSum.doubleValue());
//                                ptInstance.setZyqId(zyqId);
//                                ptInstance.setTId(id);
//                                ptInstance.setTime(new Date());
//                                ptInstance.setDescription("平台瞬产气量大于等于" + upLimit.toString());
//                                ptInstance.setFlag(0);
//                                ptInstance.setType(1);
//                                ptInstanceMapper.insert(ptInstance);
//                            }
//                            // 上一个未被处理但是 描述不一样也要添加 不处理掉上一个
//                            else if (status == 0 && !description.equals("平台瞬产气量小于等于" + upLimit.toString()) && !isEmpty) {
//                                PtInstance ptInstance = new PtInstance();
//                                if (count != 0) {
//                                    ptInstance.setRemark("其中有" + count + "个瞬量点为null");
//                                }
//                                ptInstance.setValue(valueSum.doubleValue());
//                                ptInstance.setZyqId(zyqId);
//                                ptInstance.setTId(id);
//                                ptInstance.setTime(new Date());
//                                ptInstance.setDescription("平台瞬产气量大于等于" + upLimit.toString());
//                                ptInstance.setFlag(0);
//                                ptInstance.setType(1);
//                                ptInstanceMapper.insert(ptInstance);
//
////                            ptInstanceMapper.updateLastById(lastId);
//                            }

                        }
                    }


                }
                else{
                    ptInstanceMapper.updatePtInstanceAuto(id);
                }
            }
            flag = true;
            log.info("瞬量点顺利完成扫描");
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("扫描遇到问题");
        }


    }
}
